package com.hjj.springboot.controller;

import com.hjj.springboot.entity.R;
import com.hjj.springboot.service.BaiduAiObjectService;
import com.hjj.springboot.service.BaiduAiOcrService;
import com.hjj.springboot.util.DateUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;


@RestController
@RequestMapping("/api/baiduAi")
@RequiredArgsConstructor
public class BaiduAiController {
    private final BaiduAiObjectService aiObjectService;

    private final BaiduAiOcrService aiOcrService;

    @Value("${dishImagesFilePath}")
    private String dishImagesFilePath;

    @RequestMapping("/detectObject")
    public R detectObject(@RequestParam("image") MultipartFile file) {
        try {
            // 校验图片大小（不超过4MB）
            if (file.getSize() > 4 * 1024 * 1024) {
                return R.error("图片大小超过限制");
            }

            // 调用识别服务
            String result = aiObjectService.detectObject(file);
            return R.ok(result);
        } catch (IOException e) {
            return R.error("调用服务失败");
        }
    }

    @RequestMapping("/detectOcr")
    public R detectOcr(@RequestParam("image") MultipartFile file) {
        try {
            // 调用识别服务
            String result = aiOcrService.detectOrc(file);
            return R.ok(result);
        } catch (IOException e) {
            return R.error("调用服务失败");
        }
    }

    @RequestMapping("/detectDish")
    public R detectDish(@RequestParam("image") MultipartFile file) {
        try {
            // 调用识别服务
            String result = aiObjectService.detectDish(file);
            // 保存图片到本地
            String originalFilename= file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= DateUtil.getCurrentDateStr()+suffix;
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(dishImagesFilePath+newFileName));
            HashMap<String, Object> map = new HashMap<>();
            map.put("result",result);
            map.put("image",newFileName);
            return R.ok(map);
        } catch (IOException e) {
            return R.error("调用服务失败");
        }
    }


}
